<template>
  <el-dialog
    v-model="dialogVisible"
    title="气象数据图表"
    width="1200px"
    :close-on-click-modal="false"
  >
    <!-- 图表控制面板 -->
    <div class="chart-controls">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select
            v-model="selectedStation"
            placeholder="选择监测站点"
            @change="updateChart"
          >
            <el-option label="全部站点" value="" />
            <el-option
              v-for="station in weatherStations"
              :key="station.id"
              :label="station.name"
              :value="station.id"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="chartType"
            placeholder="选择图表类型"
            @change="updateChart"
          >
            <el-option label="温度趋势" value="temperature" />
            <el-option label="湿度趋势" value="humidity" />
            <el-option label="降雨量" value="rainfall" />
            <el-option label="风速变化" value="windSpeed" />
            <el-option label="气压变化" value="pressure" />
            <el-option label="综合对比" value="comprehensive" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="updateChart"
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="refreshChart">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button @click="exportChart">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <div ref="chartRef" class="chart" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">平均温度</div>
              <div class="stat-value">{{ statistics.avgTemperature }}°C</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">最高温度</div>
              <div class="stat-value">{{ statistics.maxTemperature }}°C</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">总降雨量</div>
              <div class="stat-value">{{ statistics.totalRainfall }}mm</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">平均湿度</div>
              <div class="stat-value">{{ statistics.avgHumidity }}%</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <el-table :data="filteredData" max-height="300" stripe border>
        <el-table-column prop="stationName" label="监测站点" width="120" />
        <el-table-column prop="recordTime" label="记录时间" width="180" />
        <el-table-column prop="temperature" label="温度(°C)" width="100" />
        <el-table-column prop="humidity" label="湿度(%)" width="100" />
        <el-table-column prop="rainfall" label="降雨量(mm)" width="120" />
        <el-table-column prop="windSpeed" label="风速(m/s)" width="100" />
        <el-table-column prop="pressure" label="气压(hPa)" width="100" />
        <el-table-column prop="weather" label="天气状况" width="100" />
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

interface Props {
  visible: boolean
  chartData: any[]
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  chartData: () => []
})

const emit = defineEmits<Emits>()

// 监测站点
const weatherStations = ref([
  { id: 1, name: '西音水库主站' },
  { id: 2, name: '大坝监测站' },
  { id: 3, name: '库区中心站' },
  { id: 4, name: '入库口站' },
  { id: 5, name: '出库口站' }
])

// 图表控制
const selectedStation = ref('')
const chartType = ref('temperature')
const dateRange = ref([])
const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null

// 统计数据
const statistics = reactive({
  avgTemperature: 0,
  maxTemperature: 0,
  totalRainfall: 0,
  avgHumidity: 0
})

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 过滤后的数据
const filteredData = computed(() => {
  let data = props.chartData
  
  if (selectedStation.value) {
    data = data.filter(item => item.stationId === selectedStation.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    data = data.filter(item => {
      const recordDate = new Date(item.recordTime)
      return recordDate >= startDate && recordDate <= endDate
    })
  }
  
  return data
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return
  
  const data = filteredData.value
  
  let option: any = {}
  
  switch (chartType.value) {
    case 'temperature':
      option = getTemperatureOption(data)
      break
    case 'humidity':
      option = getHumidityOption(data)
      break
    case 'rainfall':
      option = getRainfallOption(data)
      break
    case 'windSpeed':
      option = getWindSpeedOption(data)
      break
    case 'pressure':
      option = getPressureOption(data)
      break
    case 'comprehensive':
      option = getComprehensiveOption(data)
      break
  }
  
  chartInstance.setOption(option, true)
  updateStatistics(data)
}

// 温度趋势图表配置
const getTemperatureOption = (data: any[]) => {
  const xData = data.map(item => item.recordTime.substring(5, 16))
  const yData = data.map(item => item.temperature)
  
  return {
    title: {
      text: '温度趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}°C'
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '温度(°C)'
    },
    series: [{
      name: '温度',
      type: 'line',
      data: yData,
      smooth: true,
      itemStyle: {
        color: '#ff6b6b'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(255, 107, 107, 0.3)'
          }, {
            offset: 1, color: 'rgba(255, 107, 107, 0.1)'
          }]
        }
      }
    }]
  }
}

// 湿度趋势图表配置
const getHumidityOption = (data: any[]) => {
  const xData = data.map(item => item.recordTime.substring(5, 16))
  const yData = data.map(item => item.humidity)
  
  return {
    title: {
      text: '湿度趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}%'
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '湿度(%)',
      min: 0,
      max: 100
    },
    series: [{
      name: '湿度',
      type: 'line',
      data: yData,
      smooth: true,
      itemStyle: {
        color: '#4ecdc4'
      }
    }]
  }
}

// 降雨量柱状图配置
const getRainfallOption = (data: any[]) => {
  const xData = data.map(item => item.recordTime.substring(5, 16))
  const yData = data.map(item => item.rainfall)
  
  return {
    title: {
      text: '降雨量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}mm'
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '降雨量(mm)'
    },
    series: [{
      name: '降雨量',
      type: 'bar',
      data: yData,
      itemStyle: {
        color: '#45b7d1'
      }
    }]
  }
}

// 风速变化图表配置
const getWindSpeedOption = (data: any[]) => {
  const xData = data.map(item => item.recordTime.substring(5, 16))
  const yData = data.map(item => item.windSpeed)
  
  return {
    title: {
      text: '风速变化图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}m/s'
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '风速(m/s)'
    },
    series: [{
      name: '风速',
      type: 'line',
      data: yData,
      smooth: true,
      itemStyle: {
        color: '#96ceb4'
      }
    }]
  }
}

// 气压变化图表配置
const getPressureOption = (data: any[]) => {
  const xData = data.map(item => item.recordTime.substring(5, 16))
  const yData = data.map(item => item.pressure)
  
  return {
    title: {
      text: '气压变化图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}hPa'
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '气压(hPa)'
    },
    series: [{
      name: '气压',
      type: 'line',
      data: yData,
      smooth: true,
      itemStyle: {
        color: '#feca57'
      }
    }]
  }
}

// 综合对比图表配置
const getComprehensiveOption = (data: any[]) => {
  const xData = data.map(item => item.recordTime.substring(5, 16))
  
  return {
    title: {
      text: '气象数据综合对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['温度', '湿度', '风速', '降雨量'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '温度(°C) / 湿度(%) / 风速(m/s)',
        position: 'left'
      },
      {
        type: 'value',
        name: '降雨量(mm)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '温度',
        type: 'line',
        data: data.map(item => item.temperature),
        itemStyle: { color: '#ff6b6b' }
      },
      {
        name: '湿度',
        type: 'line',
        data: data.map(item => item.humidity),
        itemStyle: { color: '#4ecdc4' }
      },
      {
        name: '风速',
        type: 'line',
        data: data.map(item => item.windSpeed),
        itemStyle: { color: '#96ceb4' }
      },
      {
        name: '降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: data.map(item => item.rainfall),
        itemStyle: { color: '#45b7d1' }
      }
    ]
  }
}

// 更新统计数据
const updateStatistics = (data: any[]) => {
  if (data.length === 0) {
    Object.assign(statistics, {
      avgTemperature: 0,
      maxTemperature: 0,
      totalRainfall: 0,
      avgHumidity: 0
    })
    return
  }
  
  const temperatures = data.map(item => item.temperature).filter(t => t != null)
  const humidities = data.map(item => item.humidity).filter(h => h != null)
  const rainfalls = data.map(item => item.rainfall).filter(r => r != null)
  
  statistics.avgTemperature = temperatures.length > 0 
    ? Number((temperatures.reduce((a, b) => a + b, 0) / temperatures.length).toFixed(1))
    : 0
  statistics.maxTemperature = temperatures.length > 0 
    ? Number(Math.max(...temperatures).toFixed(1))
    : 0
  statistics.totalRainfall = rainfalls.length > 0 
    ? Number(rainfalls.reduce((a, b) => a + b, 0).toFixed(1))
    : 0
  statistics.avgHumidity = humidities.length > 0 
    ? Number((humidities.reduce((a, b) => a + b, 0) / humidities.length).toFixed(1))
    : 0
}

// 刷新图表
const refreshChart = () => {
  updateChart()
  ElMessage.success('图表已刷新')
}

// 导出图表
const exportChart = () => {
  if (!chartInstance) return
  
  const url = chartInstance.getDataURL({
    type: 'png',
    pixelRatio: 2,
    backgroundColor: '#fff'
  })
  
  const link = document.createElement('a')
  link.download = `气象数据图表_${new Date().toISOString().substring(0, 10)}.png`
  link.href = url
  link.click()
  
  ElMessage.success('图表导出成功')
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

// 监听弹窗显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    nextTick(() => {
      initChart()
    })
  } else {
    if (chartInstance) {
      chartInstance.dispose()
      chartInstance = null
    }
  }
})

// 监听数据变化
watch(() => props.chartData, () => {
  if (chartInstance) {
    updateChart()
  }
}, { deep: true })

onMounted(() => {
  if (dialogVisible.value) {
    nextTick(() => {
      initChart()
    })
  }
})
</script>

<style scoped>
.chart-controls {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.chart-container {
  margin-bottom: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 10px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 10px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.data-table {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>